package lumis.util.parse;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.ContentHandler;

/**
 * Implementation for {@link IFileParser} to deal with {@link Parser} for most content-types. 
 *
 * @version $Revision: 11180 $ $Date: 2009-12-04 18:13:02 -0200 (Fri, 04 Dec 2009) $
 * @since 5.5.0
 */
public class TikaParser implements IFileParser
{
	/**
	 * Instance of current Tika {@link Parser} that will be used to extract data.
	 */
	private Parser parser;
	
	/**
	 * Constructor for TikaParser
	 * @param parser
	 * @since 5.5.0
	 */
	public TikaParser(Parser parser)
	{
		this.parser = parser;
	}

	public String extract(File inputFile) throws ParseException, FileNotFoundException
	{
		InputStream input = new FileInputStream(inputFile);
		return extract(input, null);
	}

	public String extract(File inputFile, Charset charset) throws ParseException, FileNotFoundException
	{
		return extract(inputFile);
	}

	public String extract(InputStream inputtream, Charset charset) throws ParseException
	{
		try
		{
			return extract(inputtream);
		}
		catch (IOException e)
		{
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public String extract(InputStream inputStream) throws ParseException, IOException
	{
		StringBuilder builder = new StringBuilder(10 * 1024);
		ContentHandler textHandler = new BodyContentHandler();
		Metadata metadata = new Metadata();			

		try
		{
			parser.parse(inputStream, textHandler, metadata);
			
			builder.append((metadata.get(Metadata.AUTHOR) != null)?metadata.get(Metadata.AUTHOR):"");
			builder.append(" ");
			
			builder.append(textHandler.toString());
			return builder.toString();
		}
		catch (Exception e)
		{
			throw new ParseException(e.getMessage(), e);
		}
		finally
		{
			try
			{
				inputStream.close();
			}
			catch (IOException e)
			{
				//ignore - no action need be taken in case the inputstream has trouble closing
			}
		}

	}

}
